package com.example.tablemainpage;

import androidx.appcompat.app.AppCompatActivity;

import android.app.ActivityOptions;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.hardware.display.DisplayManager;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {
    private VideoView videoView;
    private Button btnPause, btnFastForward, btnRewind;
    private ImageView imageView;
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        startFu();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        int ui = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        getWindow().getDecorView().setSystemUiVisibility(ui);
        getSupportActionBar().hide();

        videoView = findViewById(R.id.videoView);
        imageView = findViewById(R.id.imgPreview);
        btnPause = findViewById(R.id.btnPause);
        btnFastForward = findViewById(R.id.btnFastForward);
        btnRewind = findViewById(R.id.btnRewind);
        textView = findViewById(R.id.textView);

        Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.video);
        videoView.setVideoURI(uri);

        SharedPreferences sp = getSharedPreferences("video", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        sp.registerOnSharedPreferenceChangeListener(this);
        if (sp.getInt("time", 0) != 0) {
            textView.setText("当前播放到第" + sp.getInt("time", 0) / 1000 + "秒");
        }


        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(this, uri);
            Bitmap bitmap = retriever.getFrameAtTime(sp.getInt("time", 0));
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }

        btnPause.setOnClickListener(v -> {
            imageView.setVisibility(View.GONE);
            if (videoView.isPlaying()) {
                videoView.pause();
                editor.putInt("time", videoView.getCurrentPosition());
                editor.putBoolean("ispaly", videoView.isPlaying());
                editor.apply();
                btnPause.setText("播放");
            } else {
                editor.putBoolean("ispaly", !videoView.isPlaying());
                editor.apply();
                videoView.start();
                btnPause.setText("暂停");
            }
        });
        btnFastForward.setOnClickListener(v -> {
            int currentPosition = videoView.getCurrentPosition();
            editor.putInt("nowtime", currentPosition + 1000);
            editor.apply();
            videoView.seekTo(currentPosition + 1000); // 快进5秒
        });
        btnRewind.setOnClickListener(v -> {
            int currentPosition = videoView.getCurrentPosition();
            editor.putInt("nowtime", currentPosition - 1000);
            editor.apply();
            videoView.seekTo(currentPosition - 1000); // 后退5秒
        });

        videoView.setOnPreparedListener(mediaPlayer -> {
            videoView.seekTo(sp.getInt("time", 0));
            btnPause.setText("播放");
        });

        videoView.setOnCompletionListener(mediaPlayer -> {
            videoView.seekTo(0);
            videoView.pause();
        });
        videoView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (videoView.isPlaying()) {
                    videoView.pause();
                    editor.putBoolean("ispaly", videoView.isPlaying());
                    editor.apply();
                } else {
                    editor.putBoolean("ispaly", !videoView.isPlaying());
                    editor.apply();
                    videoView.start();
                }
            }
        });

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                imageView.setVisibility(View.GONE);
                editor.putBoolean("ispaly", !videoView.isPlaying());
                editor.apply();
                videoView.start();
            }
        });

    }

    private void startFu() {
        ActivityOptions activityOptions = ActivityOptions.makeBasic();
        DisplayManager displayManager = (DisplayManager) getApplicationContext().getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = displayManager.getDisplays();
        Intent intent = new Intent(MainActivity.this, MainFuPage.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && displays.length > 0) {
            activityOptions.setLaunchDisplayId(displays[1].getDisplayId());
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent, activityOptions.toBundle());
        } else {
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(MainActivity.this, "当前模拟器没有其他屏幕", Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sp, String s) {
        switch (s){
            case "ispaly":
                System.out.println(sp.getBoolean("ispaly", false));
                if (sp.getBoolean("ispaly",false)){
                    imageView.setVisibility(View.GONE);
                    videoView.start();
                    btnPause.setText("暂停");
                }else {
                    videoView.pause();
                    btnPause.setText("播放");
                }
                break;
            case "time":
                break;
            case "nowtime":
                videoView.seekTo(sp.getInt("nowtime",0));
                break;
        }
    }
}